package com.safety.apitest.source;

import com.safety.apitest.beans.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.HashMap;
import java.util.Random;

/**
 * @Author: QingW
 * @Date: 2021/9/17
 */
public class SourceTest4_UDF {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<SensorReading> dataStream = env.addSource(new MySensorSource());
        dataStream.print();
        env.execute("Wang-Create-JobFile");
    }


    private static class MySensorSource implements SourceFunction<SensorReading> {

        private boolean running = true;

        public void run(SourceContext<SensorReading> ctx) throws Exception {
            Random random = new Random();
            HashMap<String, Double> hashMap = new HashMap();
            for (int i = 0; i < 10; i++) {
                hashMap.put("sensor_" + (i + 1), 60 + random.nextGaussian() * 20);
            }
            while (running) {
                for (String sensorId : hashMap.keySet()) {
                    Double newTemp = hashMap.get(sensorId) + random.nextGaussian();
                    hashMap.put(sensorId, newTemp);
                    ctx.collect(new SensorReading(sensorId, System.currentTimeMillis(), newTemp));
                }
                Thread.sleep(1000L);
            }
        }

        public void cancel() {
            running = false;
        }
    }
}
